package im.frape.core;

import im.frape.model.FrapeModel;
import im.frape.model.JabberAccount;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class FrapeCore extends Service {
	private static final String TAG = "FrapeCore";
	protected static final int CHECK = 0;
	private static FrapeCore instance;
	private Handler handler;
	private FrapeModel model;

	// views
	// private ContactList contactList;

	private Timer timer = new Timer();
	private final int INTERVAL = 5 * 1000;
	private boolean started = false;

	public static FrapeCore getInstance() {
		if (instance == null) {
			Log.i(TAG, "Creating new FrapeCore");
			instance = new FrapeCore();
			instance.initialize();
		}
		return instance;
	}

	public void initialize() {
		this.model = FrapeModel.getInstance();
		this.handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case CHECK:
					Log.i(TAG, "Service got a focus.");
					FrapeModel model = FrapeModel.getInstance();
					for (JabberAccount account : model.getAccounts()) {
						if (account.isEnabled() && !account.isConnected()) {
							Log.i(TAG, account.getJabberId() + " enabled!");
							account.connect();
							if (!account.inFrapeRoster()) {
								model.addAccountRoster(account);
								account.setInFrapeRoster(true);
							}
						} else if (!account.isEnabled() && account.isConnected()) {
							Log.i(TAG, account.getJabberId() + " disabled.");
							account.disconnect();
							model.removeAccountRoster(account);
						}
					}
					;
					;
				}
			}

		};
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return (IBinder) FrapeCore.this;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		startTimer();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		stopService();
	}

	private void startTimer() {
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				FrapeCore.getInstance().handler.sendEmptyMessage(CHECK);
			}
		}, 0, INTERVAL);
	}

	private void stopService() {
		if (timer != null) {
			timer.cancel();
		}
	}

	public void addAccount(JabberAccount jabberAccount) {
		model.addAccount(jabberAccount);
	}

	public void removeAccount(JabberAccount jabberAccount) {
		model.removeAccount(jabberAccount);
	}

	public void connectAccount(JabberAccount account) {
		account.setEnabled(true);

	}

	public void disconnectAccount(JabberAccount account) {
		account.setEnabled(false);
	}

	public void isStarted(boolean b) {
		this.started = b;

	}

	public boolean isStarted() {
		return started;
	}

	public FrapeModel getModel() {

		return this.model;
	}

}
